package hello.socket;

import java.security.Principal;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

@Configuration
@EnableWebSocketMessageBroker
@ConditionalOnWebApplication
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic","/quque");//设置服务器广播消息的基础路径
        config.setApplicationDestinationPrefixes("/app"); //设置客户端订阅消息的基础路径
        //config.setPathMatcher(new AntPathMatcher(".")); //可以已“.”来分割路径，看看类级别的@messageMapping和方法级别的@messageMapping
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    	//客户端需要注册这个端点进行链接
        registry.addEndpoint("/gs-guide-websocket").
        addInterceptors(new HandshakeInterceptor() {
			//拦截器 判断用户是否登录 不登陆拦截 ,登录则获取用户信息保存
			@Override
			public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
					Map<String, Object> attributes) throws Exception {
				System.err.println("握手之前...");
				 HttpSession session = getSession(request);
				 //获取当前用户的信息
			     if(session==null || session.getAttribute("user")==null){
			            System.err.println("websocket权限拒绝");
			           // return false;
			     }else{
				     attributes.put("user",session.getAttribute("user"));
			     }
			     return true;
			}
			
			@Override
			public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
					Exception exception) {
				System.err.println("握手之后...");
			}
			
			// 参考 HttpSessionHandshakeInterceptor
		    private HttpSession getSession(ServerHttpRequest request) {
		    	
		        if (request instanceof ServletServerHttpRequest) {
		            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
		            return serverRequest.getServletRequest().getSession(false);
		        }
		        return null;
		    }
		}).
        setHandshakeHandler(new DefaultHandshakeHandler() {
        	
        	@Override
        	protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
        			Map<String, Object> attributes) {

        		return  new MyPrincipal((User) attributes.get("user"));
        	}
		}).
        setAllowedOrigins("*").withSockJS();
    }

}